<?php

namespace app\api\controller;
use app\common\controller\Api;

use Ratchet\Client\Connector;
use React\EventLoop\Factory;


/**
 * 呼叫推送
 */
class Notice extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->broadcastUrl =config('websocket.url'); // WebSocket 服务器地址
    }

    public function Notice($roomid, $shop_id,$occupants_id,$content, $targetUserId = null) {


        \app\manystore\model\Notice::create(['title'=>$content,'content'=>$content,'uid'=>$shop_id,'role'=>1,'read'=>1,'room_id'=>$roomid,'occupants_id'=>$occupants_id]);
        // 构建要发送的消息
        $message = json_encode([
            'target_user_id' => $targetUserId, // 指定的目标用户 ID
            'content' => $content,
        ]);

        // 调用 WebSocket 服务广播

        $this->broadcast($message);
    }


    private function broadcast($message) {
        $loop = Factory::create();
        $connector = new Connector($loop);

        // 连接到 WebSocket 服务器并发送消息
        $connector($this->broadcastUrl)
            ->then(function ($conn) use ($message) {
                $conn->send($message);
                //echo "Message sent: $message\n"; // Debug output
                $conn->close(); // 关闭连接
            }, function ($e) {
                //echo "Could not connect: {$e}\n"; // Debug output
            });

        $loop->run(); // 执行事件循环
    }




}
